#!/bin/bash
#
# convert.sh
# converts enron maildirs to courier maildirs, cleans them up
#
# invocation:
# ./convert.sh <directory>
# or
# /full/path/to/convert.sh <directory>
#
# The MIT License
#
# Copyright (c) 2010 Andreas Fleig
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#


function rmbad()
{
    for bad in sent_items sent _sent_mail deleted_items discussion_threads notes_inbox
    do
        if [ -e "$bad" ]
        then
            rm -r $bad
        fi
    done
}

function mkdirs()
{
    mkdir cur
    mkdir tmp
    mkdir new
}

function move_cur()
{
    while read file
    do
        bn=$(basename $file)
        if [ -e "cur/$bn" ]
        then
            newname=$(echo $file|sed 's/\//./g')
            echo "new filename: $newname"
        else
            newname=$bn
        fi
        mv "$file" "cur/$newname"
    done
}

# 
util_path=$(dirname $0)
if [ $util_path == "." ]
then
    util_path=$(pwd)
fi
echo "util path: $util_path"
pushd $1 >/dev/null

# cleanup
echo "* removing up blacklisted directories"
rmbad

echo "* removing duplicates from all_documents"
$util_path/rm_duplicates.pl $(pwd)

# move all mails from all_documents to inbox
echo "* moving messages from all_documents to inbox"
if [ -d "all_documents" ]
then
    for i in $(ls all_documents)
    do
        bn=$(basename $i)
        mv "all_documents/$i" "inbox/ad_$bn"
    done
    rm -r all_documents
fi

# directory conversion
echo "* converting directory structure"
for i in $(ls)
do
    if [ -d $i ]
    then
        mv $i .$i
        pushd .$i >/dev/null
        mkdirs
        find . -type f | move_cur
        popd >/dev/null
    fi
done

# move inbox
mv .inbox/* .
rm -r .inbox

popd >/dev/null
